package com.yfqy.app.transform;

import com.yfqy.app.constant.GeneralConstants;
import com.yfqy.app.domain.mapper.CategoryMapper;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CategoryNameTranslator {

    // 假设有一个用户服务或DAO来获取用户信息
    private final CategoryMapper categoryMapper;

    // 缓存用户信息，减少数据库查询
    private final Map<Long, String> categoryCache = new ConcurrentHashMap<>();

    public CategoryNameTranslator(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    /**
     * 转换分类ID为分类名称的通用方法
     *
     * @param t 需要转换的对象或集合
     */
    public void translationCategory(Object t) {
        if (t == null) {
            return;
        }

        try {
            if (t instanceof List<?> list) {
                // 处理集合情况
                for (Object item : list) {
                    processSingleObject(item);
                }
            } else {
                // 处理单个对象情况
                processSingleObject(t);
            }
        } catch (Exception e) {
            throw new RuntimeException("分类信息转换失败", e);
        }

    }

    /**
     * 处理单个对象的分类ID转换
     *
     * @param obj 需要处理的对象
     */
    private void processSingleObject(Object obj) throws Exception {
        if (obj == null) {
            return;
        }
        Class<?> clazz = obj.getClass();

        // 获取categoryId字段
        Field categoryIdField = getField(clazz, "categoryId");
        // 获取categoryName字段
        Field categoryNameField = getField(clazz, "categoryName");
        if (categoryIdField == null && categoryNameField == null) {
            return;
        }
        Long categoryId = GeneralConstants._L1;
        if (categoryIdField != null) {
            categoryIdField.setAccessible(true);
            categoryId = (Long) categoryIdField.get(obj);
        }
        // 如果categoryId为-1，直接返回
        if (categoryId.equals(GeneralConstants._L1)) {
            return;
        }
        // 从缓存或数据库获取用户名
        String categoryName = categoryCache.computeIfAbsent(categoryId, categoryMapper::getCategoryNameById);
        // 设置categoryName字段值
        if (categoryNameField != null) {
            categoryNameField.setAccessible(true);
            categoryNameField.set(obj, categoryName);
        }
    }

    /**
     * 获取类中的字段，包括父类的字段
     */
    private Field getField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // 尝试从父类查找
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null) {
                return getField(superClass, fieldName);
            }
            return null;
        }
    }
}
